import 'package:auto_route/auto_route.dart';
import 'package:distribution_mall_flutter/assets.dart';
import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/http_constant.dart';
import 'package:distribution_mall_flutter/constant/image_constant.dart';
import 'package:distribution_mall_flutter/constant/point_constant.dart';
import 'package:distribution_mall_flutter/entity/common/question_entity.dart';
import 'package:distribution_mall_flutter/entity/user/user.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/provider/common/article.dart';
import 'package:distribution_mall_flutter/provider/user/login.dart';
import 'package:distribution_mall_flutter/utils/common_third.dart';
import 'package:distribution_mall_flutter/utils/common_widget.dart';
import 'package:distribution_mall_flutter/utils/firebase/firebase_analytics_utils.dart';
import 'package:distribution_mall_flutter/utils/image_loader.dart';
import 'package:distribution_mall_flutter/router/router.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/widgets/third_party_login.dart';
import 'package:easy_debounce/easy_debounce.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:getwidget/getwidget.dart';
import 'package:wolt_modal_sheet/wolt_modal_sheet.dart';

final _formKey = GlobalKey<FormBuilderState>();

@RoutePage()
class LoginPage extends ConsumerStatefulWidget {
  const LoginPage({super.key});

  @override
  ConsumerState createState() => _Login();
}

class _Login extends ConsumerState<LoginPage> {
  final FocusNode _focusNode = FocusNode();
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      KeyboardVisibilityTesting.setVisibilityForTesting(true);
      _focusNode.requestFocus();
    });
  }

  SliverWoltModalSheetPage page1(BuildContext modalSheetContext,
      TextTheme textTheme, BuildContext context, QuestionEntity? params) {
    return WoltModalSheetPage(
      hasSabGradient: false,
      isTopBarLayerAlwaysVisible: true,
      backgroundColor: Colors.white,
      sabGradientColor: Colors.white,
      surfaceTintColor: Colors.white,
      navBarHeight: 50,
      trailingNavBarWidget: IconButton(
        padding: const EdgeInsets.only(right: 5),
        icon: const Icon(Icons.close),
        onPressed: Navigator.of(modalSheetContext).pop,
      ),
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.fromLTRB(15, 0, 15, 10),
        child: SingleChildScrollView(
          child: Html(
            data: params?.content ?? '',
          ),
        ),
      ),
    );
  }

  openModal(BuildContext context, QuestionEntity? params) {
    WoltModalSheet.show<void>(
      context: context,
      pageListBuilder: (modalSheetContext) {
        final textTheme = Theme.of(context).textTheme;
        return [
          page1(modalSheetContext, textTheme, context, params),
        ];
      },
      modalTypeBuilder: (context) {
        return WoltModalType.dialog;
      },
      onModalDismissedWithBarrierTap: () {
        Navigator.of(context).pop();
      },
      maxDialogWidth: 302.2,
      minDialogWidth: 302.2,
      minPageHeight: 0.8,
      maxPageHeight: 0.8,
    );
  }

  @override
  Widget build(BuildContext context) {
    final loginModal = ref.watch(loginProvider);
    final arModal = ref.watch(articleProvider);
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        leading: CommonBtnWidget.arrowBack(
          icon: Icons.arrow_back,
          // onPressed: () {
          //   RouteUtils.back();
          // }
        ),
        title: const Text(''),
        titleSpacing: 0,
        flexibleSpace: Container(
          color: const Color.fromRGBO(245, 246, 248, 0.9),
          // color: Colors.black,
          // decoration: const BoxDecoration(
          //     gradient: LinearGradient(
          //         begin: Alignment.topCenter,
          //         end: Alignment.bottomCenter,
          //         colors: [
          //   Color.fromRGBO(245, 246, 248, 1),
          //   // Colors.black,
          //   // Colors.black,
          // ],
          //         stops: [
          //   0.02,
          // ]))
        ),
      ),
      body: Container(
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.symmetric(horizontal: EdgeConstant.edge218),
        decoration: const BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
              Color.fromRGBO(245, 246, 248, 0.9),
              Colors.white
              // Colors.black
              // Colors.black,
              // Colors.black,
            ],
                stops: [
              0,
              0.2
            ])),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(
                  height: 40,
                ),
                ImageLoader.imageAsset(ImageLocalConstant.epalTextLogo,
                    width: 118.3, height: 38.2),
                Container(
                  padding: const EdgeInsets.only(
                      top: 35.5, bottom: EdgeConstant.edge218),
                  child: Text(
                    S.current.user_login_log_sign,
                    style: const TextStyle(
                      color: Colors.black,
                      fontSize: 18.2,
                    ),
                  ),
                ),
                // LoginSwiper()
                FormBuilder(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      FormBuilderTextField(
                        name: 'phone',
                        // focusNode: _focusNode,
                        inputFormatters: [
                          LengthLimitingTextInputFormatter(11),
                          FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))
                        ],
                        validator: FormBuilderValidators.compose([
                          FormBuilderValidators.required(
                              errorText: S.current.address_please_phone),
                          FormBuilderValidators.match(RegularConstant.phpPhoe,
                              errorText: S.current.address_phone_error_format),
                        ]),
                        autovalidateMode: AutovalidateMode.onUserInteraction,
                        textAlign: TextAlign.left,
                        textAlignVertical: TextAlignVertical.center,
                        decoration: InputDecoration(
                          hintText: S.current.user_login_mobile_replace,
                          prefixIcon: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Container(
                                margin: const EdgeInsets.only(top: 2),
                                child: const Text(
                                  '+63',
                                  textAlign: TextAlign.center,
                                  style:
                                      TextStyle(color: ColorConstant.grey114),
                                ),
                              ),
                            ],
                          ),
                          constraints: const BoxConstraints(
                              minHeight: 43.4, maxHeight: 70),
                          contentPadding:
                              const EdgeInsets.symmetric(horizontal: 5),
                          // enabledBorder: const OutlineInputBorder(
                          //     borderSide: BorderSide(
                          //         color: ColorConstant.grey233, width: 0.9),
                          //     borderRadius: BorderRadius.all(
                          //         Radius.circular(RadiusConstant.edge10))),
                          // errorBorder: const OutlineInputBorder(
                          //     borderSide: BorderSide(
                          //         color: Color.fromRGBO(255, 0, 0, 1),
                          //         width: 0.9),
                          //     borderRadius: BorderRadius.all(
                          //         Radius.circular(RadiusConstant.edge10))),
                          // focusedErrorBorder: const OutlineInputBorder(
                          //     borderSide: BorderSide(
                          //         color: Color.fromRGBO(255, 0, 0, 0.7),
                          //         width: 0.9),
                          //     borderRadius: BorderRadius.all(
                          //         Radius.circular(RadiusConstant.edge10))),
                          // focusedBorder: const OutlineInputBorder(
                          //     borderSide:
                          //         BorderSide(color: Colors.black, width: 0.9),
                          //     borderRadius: BorderRadius.all(
                          //         Radius.circular(RadiusConstant.edge10))),
                          // hintStyle: const TextStyle(
                          //     color: Color.fromRGBO(119, 119, 119, 1),
                          //     fontSize: FontConstant.f12,
                          //     textBaseline:
                          //         TextBaseline.alphabetic, // 设置文本基线为基准线
                          //     letterSpacing: TextConstant.letterSpacing),
                        ),
                        keyboardType: TextInputType.number,
                        style: const TextStyle(
                          fontSize: FontConstant.f16, // 设置字体大小为20
                        ),
                        onChanged: (str) {
                          ref.watch(loginProvider.notifier).setShowError(
                              str?.isNotEmpty == true && str!.length >= 10
                                  ? true
                                  : false);
                        },
                      )
                    ],
                  ),
                ),

                // ConstrainedBox(
                //   constraints: const BoxConstraints(
                //     minHeight: 40,
                //     maxHeight: 72.8,
                //   ),
                // ),
                const SizedBox(
                  height: 36.4,
                ),
                CommonBtnWidget.generalBtn(
                    isLoading: isLoading,
                    loginModal.showError
                        ? () {
                            if (_formKey.currentState?.validate() != true) {
                              return;
                            }
                            _formKey.currentState?.save();
                            Map<String, dynamic>? map =
                                _formKey.currentState?.value;
                            if (map == null) {
                              EPToast.showToast(S.current.user_login_re_enter);
                              return;
                            }
                            if (isLoading) return;
                            FirebaseAnalyticsUtils.logEvent(
                                name: PointConstant.clickCode);
                            isLoading = true;
                            setState(() {});
                            String formatPhone = '+63${map['phone']}';
                            Map<String, dynamic> map2 = {
                              'receiver': formatPhone,
                              'receiverType': ReceiverType.phone,
                              'endpoint': HttpConstant.getDomain.currTerminal
                            };
                            ref
                                .read(loginProvider.notifier)
                                .setAccount(formatPhone);
                            ref.read(loginProvider.notifier).setParams(map2);
                            ref
                                .read(loginProvider.notifier)
                                .getCode(map2)
                                .then((AutoCodeEntity? data) {
                              if (data == null) {
                                isLoading = false;
                                return;
                              }
                              appRouter.push(
                                  LoginVerificationRoute(phone: map['phone']));
                              ref
                                  .read(loginProvider.notifier)
                                  .startTime(data.sendCoolDownSecond ?? 30);
                            }).whenComplete(() {
                              isLoading = false;
                              setState(() {});
                            });
                          }
                        : null,
                    shape: GFButtonShape.square,
                    width: double.infinity,
                    height: 43.7,
                    radius: 7.3,
                    text: S.current.NEXT,
                    textStyle: const TextStyle(
                        color: Colors.white,
                        fontSize: FontConstant.f16_4,
                        fontWeight: FontWeight.bold,
                        letterSpacing: TextConstant.letterSpacing)),
                const SizedBox(
                  height: 72.8,
                ),
                if (!kIsWeb) const ThirdPartyLogin(),
              ],
            ),
            const Expanded(child: SizedBox.shrink()),
            DefaultTextStyle(
                style: const TextStyle(
                    fontSize: FontConstant.f127,
                    color: Color.fromRGBO(134, 141, 150, 1),
                    letterSpacing: TextConstant.letterSpacing),
                child: Column(
                  children: [
                    Text(S.current.user_login_by_loggin),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        GestureDetector(
                          onTap: () {
                            openModal(context, arModal.tremsData);
                          },
                          child: Text(S.current.terms_services,
                              style: const TextStyle(
                                  decoration: TextDecoration.underline)),
                        ),
                        const Text(' & '),
                        GestureDetector(
                          onTap: () {
                            openModal(context, arModal.privacyData);
                          },
                          child: Text(S.current.privary_policy,
                              style: const TextStyle(
                                  decoration: TextDecoration.underline)),
                        )
                      ],
                    )
                  ],
                )),
            SizedBox(
              height: MediaQuery.of(context).padding.bottom + 41,
            )
          ],
        ),
      ),
    );
  }
}
